import datetime
import time
from . import index_blu
from flask import render_template, request, jsonify, session, redirect, url_for
from app import sql
from app.models.model import News, User, Collection, Comment
from werkzeug.security import generate_password_hash, check_password_hash

# 首页
@index_blu.route("/")
def index():
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except:
        page = 1
    a = sql.session.query(News).order_by(News.create_time.desc()).paginate(page, 12, False)
    user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    tie = sql.session.query(News).order_by(News.clicks.desc()).paginate(1, 10, False)
    if user:
        # 昨天时间
        today = datetime.date.today()
        yesterday = today - datetime.timedelta(days=1)
        # 昨天开始时间戳
        yesterday_start_time = int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))
        # 昨天结束时间戳
        yesterday_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) - 1
        user.T_F_sign = 1
        if user.sign_in_time == 0 or yesterday_start_time <= user.sign_in_time <= yesterday_end_time:
            user.T_F_sign = 0
    return render_template("index.html", num=1, news=a, user=user, tie=tie)


# 切换状态， 提问，分享，讨论
@index_blu.route("/zt")
def share():
    are = request.args.get("are")
    page = request.args.get("page")
    if page:
        try:
            page = int(page)
        except:
            page = 1
    else:
        page = 1
    num = 1
    if are == "fx":
        num = 2
    elif are == "tl":
        num = 3
    a = sql.session.query(News).filter(News.category_id == num).order_by(News.create_time.desc()).paginate(page, 12, False)
    user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    tie = sql.session.query(News).order_by(News.clicks.desc()).paginate(1, 10, False)
    if user:
        user.T_F_sign = 1
        if user.sign_in_time == 0:
            user.T_F_sign = 0
    return render_template("index.html", num=are, news=a, user=user, tie=tie)


# 帖子的内容
@index_blu.route("/detail/<are>")
def detail(are):
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except:
        page = 1

    a = sql.session.query(News).filter(News.id == are).first()
    user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    comment = sql.session.query(Comment).filter(Comment.news_id == are).order_by(Comment.news_id.desc()).paginate(page, 5, False)
    if not comment:
        comment = sql.session.query(Comment).filter(Comment.news_id == are).order_by(Comment.news_id.desc()).paginate(
            1, 5, False)

    coll = None
    if user:
        coll = sql.session.query(Collection).filter(Collection.user_id == user.id, Collection.news_id == are).first()
    for i in comment.items:
        if i.comment_user:
            hf = sql.session.query(Comment).filter(Comment.id == i.comment_user).first()
            i.hf = hf
    return render_template("jie/detail.html", tie=a, user=user, coll=coll, comment=comment)


# 签到
@index_blu.route("/sign_in", methods=["POST"])
def sign_in():
    if session.get("user_email"):
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        # 昨天时间
        today = datetime.date.today()
        yesterday = today - datetime.timedelta(days=1)

        # 昨天开始时间戳
        yesterday_start_time = int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))

        # 昨天结束时间戳
        yesterday_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) - 1

        tomorrow = today + datetime.timedelta(days=1)
        # 今天开始时间戳
        today_start_time = yesterday_end_time + 1
        # 今天结束时间戳
        today_end_time = int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d'))) - 1

        if a.sign_in_time == 0 or yesterday_start_time <= a.sign_in_time <= yesterday_end_time:
            ret = {"status": 0, "msg": "签到成功"}
            a.continuous_sign_in += 1
            sign_in_times = str(time.time())
            a.sign_in_time = int(sign_in_times[:sign_in_times.rfind(".")])
            if a.continuous_sign_in < 5:
                a.award += 5
            elif 5 <= a.continuous_sign_in < 15:
                a.award += 10
            elif 15 <= a.continuous_sign_in < 30:
                a.award += 15
            elif 30 <= a.continuous_sign_in:
                a.award += 20
            sql.session.commit()
            return jsonify(ret)
        elif today_start_time <= a.sign_in_time <= today_end_time:
            ret = {"status": 6003, "msg": "今天已签到"}
            return jsonify(ret)

    ret = {"status": 6002, "msg": "请先登录"}
    return jsonify(ret)


# 找回密码
@index_blu.route("/reset_pass", methods=["GET", "POST"])
def reset_pass():
    if request.method == "GET":
        email = request.args.get("email")
        token = request.args.get("token")
        user = sql.session.query(User).filter(User.email == email).first()
        if not user or user.forget != token:
            return render_template("other/404.html")
        return render_template("user/reset.html", email=email)
    elif request.method == "POST":
        email = request.form.get("email")
        pwd1 = request.form.get("pass")
        pwd2 = request.form.get("repass")
        img_code = request.form.get("vercode")
        if not all([email, pwd1, pwd2, img_code]):
            ret = {"status": 4008, "msg": "缺少数据"}
            return jsonify(ret)
        user = sql.session.query(User).filter(User.email == email).first()
        if not user:
            ret = {"status": 4009, "msg": "数据错误"}
            return jsonify(ret)
        if pwd1 == pwd1:
            if 6 <= len(pwd1) <= 16:
                user.password_hash = generate_password_hash(pwd1)
                user.forget = "0"
                sql.session.commit()
                ret = {"status": 0, "msg": "更换成功"}
                return jsonify(ret)
            ret = {"status": 5005, "msg": "密码只能是6到16位"}
            return jsonify(ret)
        ret = {"status": 5006, "msg": "两次密码不一样"}
        return jsonify(ret)
    ret = {"status": 5008, "msg": "请求错误"}
    return jsonify(ret)
